#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2025/1/6 18:16
# @Author : ZhengQL

import json
import os
from swagger_parser import SwaggerParser
from openpyxl import Workbook

class Swagger_Handler:
    def generate_test_cases(self, swagger_path, output_format='json'):

        """
        根据Swagger文档生成测试用例
        :param swagger_path: Swagger文档的路径
        :param output_format: 输出格式，支持'json'和'excel'
        """
        def __init__(self, swagger_path, output_format='json'):
            pass

        # 解析swagger文档
        swagger_data = SwaggerParser.pares_from_file(swagger_path)
        paths = SwaggerParser.get_paths(swagger_data)

        # 初始化用例列表
        test_cases = []

        # 遍历所有的路径和HHP方法
        for path, methods in paths.items():
            for method, operation in methods.items():
                # 获取请求参数和响应参数
                perameters = SwaggerParser.get_operation_parameters(operation)
                responses = SwaggerParser.get_operation_response(operation)


                # 构建测试用例
                test_case = {
                    'path': path,
                    'method': method,
                    'perameters':[param['name'] for param in perameters],
                    'expected_status_code':responses[0]['code'],
                    'expected_response':responses[0]['description']
                }

                # 添加到测试用例列表
                test_cases.append(test_case)
                print(test_case)

        # 根据输出格式生成文件
        if output_format == 'json':
            with open('test_cases.json', 'w') as f:
                json.dump(test_cases, f, indent=4)
        elif output_format == 'excel':
            # 创工作薄和工作表
            workbook = Workbook()
            sheet = workbook.active

            # 写入表头
            sheet.append(['Path', 'Method', 'Parameters', 'Expected Status Code', 'Expected Response'])

            # 写入测试用例数据
            for test_case in test_cases:
                sheet.append([test_case['path'], test_case['method'], test_case['perameters'], test_case['expected_status_code'], test_case['expected_response']])

            # 保存excel文件
            workbook.save(test_cases.xlsx)

# 使用示例
swagger_path = 'swagger.json'
Swagger_Handler.generate_test_cases(swagger_path, output_format='excel')